package com.sz.classload;

import java.util.HashMap;
import java.util.Map;

/**
 * 重写equals为什么必须重写hashCode
 *
 * 使哈系表容器可以正常工作
 */
public class EqualsHashCode {

    public static void main(String[] args) {
        A a1 = new A();
        A a2 = new A();

        System.out.println("EqualsHashCode.main "+ a1.equals(a2));

        System.out.println("EqualsHashCode.main hashCode "+ (a1.hashCode() == a2.hashCode()) );

        Map<String,String> map = new HashMap<>();
        map.put("a","aedafd");
        map.put("a","dddd");

        System.out.println("EqualsHashCode.main map size "+map.size());

        Map<A,String> map2 = new HashMap<>();
        map2.put(a1,"as");
        map2.put(a2,"dad");

        System.out.println("EqualsHashCode.main map2 A size "+map2.size());

    }

    private static class A{
        private int a = 1;
        private int b = 2;

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            A a1 = (A) o;

            if (a != a1.a) return false;
            return b == a1.b;
        }

        @Override
        public int hashCode() {
            int result = a;
            result = 31 * result + b;
            return result;
        }
    }
}
